import { defineStore } from 'pinia'
import { DefaultShareConfig } from '@/api/config.js'
import $mUtils from '@/common/utils'
import * as $apis from '@/api/'

interface Address {
	id?: string
	province?: string
	area?: string
	city?: string
	address?: string
	mobile?: string
	name?: string
	locate_address?: string
}

export const user = defineStore('user', {
	// 开启后对 state 的数据读写都将持久化
	unistorage: true,
	// Store
	state: () => {
		return {
			userData: {
				expires_in: 0, // 有效期
				hasLogin: false, // 是否登录
				access_token: '', // 用户Token
				userInfo: {
					id: 0,
					mobile: '',
					avatar: DefaultShareConfig.logo,
					name: DefaultShareConfig.platform
				}
			},
			address: {} as Address // 地址编辑
		}
	},
	// Getters
	getters: {
		// 用户是否登录
		hasLogin(): boolean {
			if (this.userData.access_token && this.userData.hasLogin) {
				return true
			}
			return false
		}
	},
	// Actions
	actions: {
		// 登录更新状态
		login(data: any) {
			this.userData.hasLogin = true
			this.userData.expires_in = data.expires_in
			this.userData.access_token = data.access_token
		},
		// 退出更新状态
		logout() {
			this.userData.hasLogin = false
			this.userData.expires_in = 0
			this.userData.access_token = ''
			this.userData.userInfo = {
				id: 0,
				mobile: '',
				avatar: DefaultShareConfig.logo,
				name: DefaultShareConfig.platform
			}
		},
		// 获取用户信息
		getUsers() {
			return new Promise(resolve => {
				$apis.getUsers().then((res: any) => {
					if (res.code == 0) {
						resolve(res.data)
						this.userData.userInfo = res.data
					}
				})
			})
		},
		// 登录过期 重新登录
		reLogin(data: any = { pages: null, refresh: false }) {
			/**
			 * @param 刷新页面无需退出登录
			 * @param pages指定重定向页面
			 * @param refresh是否只刷新页面
			 */
			if (!data.refresh) this.logout()

			let pages = getCurrentPages()
			let e: any = data.pages || pages[pages.length - 1]

			let whiteList = ['pages/login/login', 'pages/login/bindMobile']

			if (whiteList.includes(e.route)) {
				e.route = 'pages/index/index'
			}

			// 登录成功后的重定向地址和参数
			let query = {
				redirectUrl: '/' + e.route,
				...(e.options || e.query)
			}

			console.log('登录过期 重新登录', query)

			if (data.refresh) {
				// 刷新页面
				uni.reLaunch({
					url: $mUtils.objParseUrlAndParam({ path: query.redirectUrl, query })
				})
			} else {
				// 重新登录
				uni.reLaunch({
					url: $mUtils.objParseUrlAndParam({ path: '/pages/login/login', query })
				})
			}
		},
		// 存储编辑地址
		updateAddressInfo(data: any) {
			this.address = data
		}
	}
})
